package TruongNhaLib;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import SessionManager.CookieManager;
import android.content.Context;
import android.os.StrictMode;
import android.util.Log;
 
public class JSONParser {
	//static DefaultHttpClient httpClientStatic = new DefaultHttpClient();
	private static DefaultHttpClient client;
	static DefaultHttpClient httpClientStatic = JSONParser.getThreadSafeClient();
    static InputStream is = null;
    static JSONObject jObj = null;
    static JSONArray jArr = null;
    static String json = "";
 
    // constructor
    public JSONParser() {
    	Log.d("parser constructer ", "construnctor");
        //This snipset allow stricmode in android network. It should be allow from android 3.0 and later
		StrictMode.ThreadPolicy policy = new StrictMode.
		ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
    }
    //Test parsing without parameters:
    public static JSONObject getJSONFromUrl(String url) {
    	Log.e("JSON", "01 ");
        // Making HTTP request
    	InputStream is = null;
        try {
        	Log.e("JSON", "02 ");

        	// defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
        	Log.e("JSON", "03 ");
            HttpResponse httpResponse = httpClient.execute(httpPost);
            Log.e("JSON", httpResponse.getStatusLine().toString());
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();            
        	Log.e("JSON", "04 ");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    	Log.e("JSON", "05 ");

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
        	Log.e("JSON", "06 ");

            StringBuilder sb = new StringBuilder();
            String line = null;
        	Log.e("JSON", "07 ");

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
    	Log.e("JSON", "08 ");

        // try parse the string to a JSON object
        try {
        	Log.e("JSON", "09 ");

            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
    	Log.e("JSON", "10 ");

        // return JSON String	
        Log.d("JSON Parser result: ", "done"+ json);
        return jObj;
	}//End  test parsing JSON.  
    
    
    
    /*
     * 1. HttpGet:  return 200 Ok + csrftoken + cookies
     * 2. HttpPost: params: middlewarecsrftoken: --------------------
     * 						cookies: --------------
     * 						username: ---------
     * 						pass: --------
     * 3. Done
     * */
    public JSONObject getJSONFromUrl(Context context,String url, List<NameValuePair> params) {
        // Making post request with username & password to login
    	InputStream is = null;
        try {
            // defaultHttpClient
            //DefaultHttpClient httpClient = new DefaultHttpClient();
            Log.e("JSON", "In login user 02.2");
            HttpPost httpPost = new HttpPost(url);
            
            Log.e("JSON", "In login user 02.3");
            
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            
            Log.e("JSON", "In login user 02.4");
            //HttpResponse httpResponse = httpClientStatic.execute(httpPost);
            HttpResponse httpResponse = JSONParser.getThreadSafeClient().execute(httpPost);
            Log.e("JSON POST", httpResponse.getStatusLine().toString() +"-");
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

           	//List<Cookie> 
            List<Cookie> cookies = JSONParser.getThreadSafeClient().getCookieStore().getCookies();
            CookieManager.saveCookies(context, cookies);
            if (cookies.isEmpty()) {
            	Log.e("COOKIES post: ",  "Empty Cookies");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    Log.e("COOKIES post: ", cookies.get(i).getName()+"--"+ cookies.get(i).getValue());
                }
            }
            Log.e("JSON", "In login user 02.6");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e("JSON", "In login user 02.7");
        //Read httpResponse to String
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            Log.e("JSON", "In login user 02.8");
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            Log.e("JSON", "In login user 02.9");
            is.close();
            Log.e("JSON",  sb.toString());
            json = sb.toString();
            Log.e("JSON",  json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        // Try parse the string to a JSON object
        if( !json.equals("")){
	        try {
	            jObj = new JSONObject(json);
	            jObj.put("success", "1");
	        } catch (JSONException e) {
	            Log.e("JSON Parser", "Error parsing data " + e.toString());
	        }
        } else{
	        Log.e("JSON Parser", "Empty json response");
	        try {
	            jObj = new JSONObject();
	            jObj.put("success", "0");
	        } catch (JSONException e) {
	            Log.e("JSON Parser", "Error parsing data " + e.toString());
	        }
        }
        // return JSON String
        return jObj;
    }
    public String getCsrfFromUrl(String url) {
        // Making HTTP GET request to get csrfmiddlewaretoken:
    	InputStream is = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            //HttpResponse httpResponse = httpClientStatic.execute(httpGet);      
            HttpResponse httpResponse = JSONParser.getThreadSafeClient().execute(httpGet);
            Log.e("JSON GET", httpResponse.getStatusLine().toString() +"-");
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
           	//List<Cookie> 
            List<Cookie> cookies = JSONParser.getThreadSafeClient().getCookieStore().getCookies();
            if (cookies.isEmpty()) {
            	Log.e("COOKIES post: ",  "Empty Cookies");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    Log.e("COOKIES post: ", cookies.get(i).getName()+"--"+ cookies.get(i).getValue());
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }      
        //Read httpResponse to String
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            Log.e("JSON", "In login user 02.8");
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON",  json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
            return null;
        }
        // Try parse the string to a JSON object, Find csrfmiddlewaretoken
        if( !json.equals("")){
	        try {
	            jObj = new JSONObject(json);		
	            Log.e("JSON csrfmiddlewaretoken", jObj.getString("csrfmiddlewaretoken"));
	            return jObj.getString("csrfmiddlewaretoken");
	        } catch (JSONException e) {
	            Log.e("JSON Parser", "Error parsing data " + e.toString());
	        }
        }
        Log.e("JSON Parser", "Empty response ");
	    return null;    
    }
    //Return jsonObject
    public static JSONObject getStudentList(String url) {
        // Making HTTP GET request to get studentList:
        Log.e("URL", url);
        InputStream is = null;
    	try {
            HttpGet httpGet = new HttpGet(url);
            //HttpResponse httpResponse = httpClientStatic.execute(httpGet);      
            HttpResponse httpResponse = JSONParser.getThreadSafeClient().execute(httpGet);
            Log.e("JSON GET", httpResponse.getStatusLine().toString() +"-");
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        //Read httpResponse to String
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            Log.e("JSON", "In getStudentList ");
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON",  json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
            return null;
        }
 
        // Try parse the string to a JSON object
        if( !json.equals("")){
	        try {
	            jObj = new JSONObject(json);
	        } catch (JSONException e) {
	            Log.e("JSON Parser", "Error parsing data " + e.toString());
	        }
        }
	    return jObj;    
    }
    //Return json array
    public JSONArray getStudentArray(String url) {
        // Making HTTP GET request to get studentList:
        Log.e("URL", url);
        InputStream is = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = JSONParser.getThreadSafeClient().execute(httpGet);
            Log.e("JSON GET", httpResponse.getStatusLine().toString() +"-");
            HttpEntity httpEntity= httpResponse.getEntity();
            is = httpEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }        
        //Read httpResponse to String
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            Log.e("JSON", "In getStudentList ");
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON",  json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
            return null;
        }
        
        JSONArray jArray = null;
        // Try parse the string to a JSON object
        if( !json.equals("")){
	    	try {
	    		jArray = new JSONArray(json);
	        } catch (JSONException e) {
	            Log.e("JSON Parser", "Error parsing data " + e.toString());
	        }
        }
        return jArray;    
    }
    /*
     * Get json object from url
     */
    public JSONObject getJSONObject(String url) {
		// TODO Auto-generated method stub
        // Making HTTP GET request to get studentList:
        Log.e("URL", url);
        InputStream is = null;
    	try {
            HttpGet httpGet = new HttpGet(url);
            //HttpResponse httpResponse = httpClientStatic.execute(httpGet);      
            HttpResponse httpResponse = JSONParser.getThreadSafeClient().execute(httpGet);
            Log.e("JSON GET", httpResponse.getStatusLine().toString() +"-");
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        //Read httpResponse to String
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON",  json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
            jObj = new JSONObject();
            try {
				jObj.put("error", "Error convert buffer stream to string");
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
            return jObj;
        }
 
        // Try parse the string to a JSON object
        if( !json.equals("")){
	        try {
	            jObj = new JSONObject(json);
	        } catch (JSONException e) {
	            jObj = new JSONObject();
	            try {
					jObj.put("error", "Server busy, please try again");
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
	            return jObj;
	        }
        }
	    return jObj;    
	}
    /*
     * Get json array from url
     */
    public JSONArray getJSONArray(String url) {
        Log.e("URL", url);
        jArr = new JSONArray();
        InputStream is = null;
    	try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = JSONParser.getThreadSafeClient().execute(httpGet);
            Log.e("JSON GET", httpResponse.getStatusLine().toString() +"-");
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            jArr.put("UnsupportedEncodingException e");
            return jArr;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            jArr.put("ClientProtocolException e");
            return jArr;
        } catch (IOException e) {
            e.printStackTrace();
            jArr.put("IOException e");
            return jArr;
        }
        //Read httpResponse to String
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON",  json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
            jArr = new JSONArray();
            jArr.put("Server error buffer -> string");
            return jArr;
        }
 
        // Try parse the string to a JSON object
        if( !json.equals("")){
	        try {
	            jArr = new JSONArray(json);
	        } catch (JSONException e) {
	            jArr = new JSONArray();
	            jArr.put("Server busy (json format)");
	            return jArr;
	        }
        }
	    return jArr;    
	}
     /*Post attendance result to server:*/
    //This function is replaced by post submit. remove later. 
     
    public int postStudentList(String postStudentListURL, List<NameValuePair> params){
        int statusCode = 0;
        Log.e("JSON POst Student list", "01");
        try {
            Log.e("JSON POst Student list", "02");
        	// defaultHttpClient
            //DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(postStudentListURL);
            Log.e("JSON POst Student list", "03");
            
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            Log.e("JSON POst Student list", "035");
            HttpResponse httpResponse = JSONParser.getThreadSafeClient().execute(httpPost);
            Log.e("JSON POst Student list", "04");

            statusCode = httpResponse.getStatusLine().getStatusCode();
            Log.e("JSON POst Student list", statusCode+"-");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e("JSON POst Student list", "05");
    	return statusCode;
    }//end function
  
    /*
     * function: postSubmit(URL, params)
     * To post any params you want to URL: student attendenca list or student mark.
     * The params include csrfToken, too.
     */
    public int postSubmit(String URL, List<NameValuePair> params){
        int statusCode = 0;
        Log.e("JSON submit", "01");
        try {
            Log.e("JSON submit", "02");
        	// defaultHttpClient
            //DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(URL);
            Log.e("JSON submit", "03");
            
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            Log.e("JSON submit", "035");
            HttpResponse httpResponse = JSONParser.getThreadSafeClient().execute(httpPost);
            Log.e("JSON submit", "04");

            statusCode = httpResponse.getStatusLine().getStatusCode();
            Log.e("JSON submit", statusCode+"-");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e("in JSONParser URL", URL);
    	return statusCode;
    }//end function
    
    public static DefaultHttpClient getThreadSafeClient() {
    	if(client != null){
    		return client;
    	}
    	client = new DefaultHttpClient();
    	ClientConnectionManager mgr = client.getConnectionManager();
    	HttpParams params = client.getParams();
    	client = new DefaultHttpClient(new ThreadSafeClientConnManager(params,
    	mgr.getSchemeRegistry()), params);
    	return client;
    }
	public boolean isSavedSession(Context context) {
		if(CookieManager.isSaved(context)){
			List<Cookie> cookies = CookieManager.getCookies(context);
			for (Cookie cookie : cookies) {
				client.getCookieStore().addCookie(cookie);
			}
			return true;
		}
		return false;
	}
	public void clearSession(Context context){
		CookieManager.clear(context);
	}
	
}//end class